var mongoose = require('mongoose');
var upload = require("../model/upload");
var Cate=require('../model/cate');
var fs = require('fs');
module.exports={
    list(req,res,next){
        var page=(req.body.page)?req.body.page:1;
        var limit=(req.body.limit)?req.body.limit:2;
        var id=req.body.menuid;
        console.log(id);
        Cate.findOne({_id:id},function(err,doc){
            if(!doc){
                res.json('分类不存在');
            }
            ids=[doc._id]
            doc.getChildren(function(err, docs){
                console.log(docs);
                for(let i=0;i<docs.length;i++){
                    ids.push(docs[i]._id);
                }
                upload.paginate({menuid:{$in:ids}},{page:page,limit:limit},(error,results)=>{
                    if(error){
                        console.log(error)
                    }
                    else{
                        res.json(results);
                    }
                })
            })
        })
    },
    post(req,res,next){
        var fileInfo={...req.file};
        fileInfo.menuid=req.body.id;
        console.log(fileInfo);
        const comment=new upload(fileInfo);
        comment.save(function(error,result){
            if(error){
                res.json(error);
            }
            else{
                res.json(result);
            }
        })
    },
    put(req,res,next){
        const id=req.params.id;
        upload .findByIdAndUpdate(id,{$set:req.body},{new:false}).then((result)=>{
                    res.json(result);
            })
    },
    delete(req,res,next){
        const id=req.params.id;
        upload.findByIdAndRemove(id,function(error,result){
            if(error){
                console.log(error)
            }
            else{
                res.json("delete is ok!")
            } 
           
        })
    },
    getFile(req,res,next){
        const path=req.query.path;
        console.log(path)
        fs.stat('../public/'+path, function (err, data) {
            if(err) {
             res.send(err);
             return;
            }
           res.send(data);
        })
    }
}